import React, { useState, useEffect } from 'react';
import { View, Text, StyleSheet, FlatList, TouchableOpacity, Image, ActivityIndicator, TextInput, Dimensions } from 'react-native';
import { searchBooks } from '../src/services/bookService';
import Icon from 'react-native-vector-icons/FontAwesome';

const { width } = Dimensions.get('window');
const ITEM_MARGIN = 10;
const ITEM_WIDTH = (width - ITEM_MARGIN * 3) / 2; // 两列布局，左右和中间各有10的间距

// 添加类别颜色映射
const categoryColors = {
    '玄幻': '#FFE4E1',
    '修真': '#E6E6FA',
    '都市': '#F0FFF0',
    '历史': '#FFF0F5',
    '网游': '#F0F8FF',
    '科幻': '#F5F5DC',
    '其他': '#FFE4C4',
};

const Search = ({ route, navigation }) => {
    const { keyword, category } = route.params || {};
    const [books, setBooks] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [searchValue, setSearchValue] = useState(keyword || category || '');

    const formatDate = (dateString) => {
        const date = new Date(dateString);
        return `${date.getFullYear()}年${(date.getMonth() + 1).toString().padStart(2, '0')}月${date.getDate().toString().padStart(2, '0')}日`;
    };

    useEffect(() => {
        setSearchValue(keyword || category || '');
        fetchBooks();
    }, [keyword, category]);

    const fetchBooks = async () => {
        try {
            setLoading(true);
            setError(null);
            const params = {
                sort: '-update_time'
            };
            if (category && category !== '全部') {
                params.category = category;
            }
            if (keyword) {
                params.q = keyword;
            }
            const data = await searchBooks(params);
            setBooks(data);
        } catch (error) {
            console.error('Error fetching books:', error);
            setError(error.message);
        } finally {
            setLoading(false);
        }
    };

    const handleSearch = () => {
        if (searchValue.trim()) {
            navigation.setParams({ keyword: searchValue.trim() });
        }
    };

    const renderBookItem = ({ item }) => (
        <TouchableOpacity
            style={styles.bookItem}
            onPress={() => navigation.navigate('BookContent', { bookId: item.id })}
        >
            <View style={styles.imageContainer}>
                <Image
                    source={{ uri: item.image || 'https://via.placeholder.com/150x200/e0e0e0/757575?text=Book' }}
                    style={styles.bookCover}
                />
                <View style={[
                    styles.categoryTag,
                    { backgroundColor: categoryColors[item.category] || categoryColors['其他'] }
                ]}>
                    <Text style={styles.categoryText}>{item.category}</Text>
                </View>
            </View>
            <View style={styles.bookInfo}>
                <Text style={styles.bookTitle} numberOfLines={1}>{item.title}</Text>
                <Text style={styles.bookAuthor} numberOfLines={1}>{item.author}</Text>
                <Text style={styles.updateTime}>
                    {formatDate(item.update_time)}
                </Text>
                <Text style={styles.commentCount}>{item.comment_count} 评论</Text>
            </View>
        </TouchableOpacity>
    );

    if (loading) {
        return (
            <View style={styles.loadingContainer}>
                <ActivityIndicator size="large" color="#70a1ff" />
            </View>
        );
    }

    return (
        <View style={styles.container}>
            <View style={styles.searchBar}>
                <TouchableOpacity onPress={handleSearch} style={styles.searchIcon}>
                    <Icon name="search" size={20} color="#999" />
                </TouchableOpacity>
                <TextInput
                    style={styles.searchInput}
                    placeholder="搜索书籍"
                    placeholderTextColor="#999"
                    value={searchValue}
                    onChangeText={setSearchValue}
                    onSubmitEditing={handleSearch}
                    returnKeyType="search"
                />
                {searchValue ? (
                    <TouchableOpacity onPress={() => setSearchValue('')}>
                        <Icon name="times-circle" size={18} color="#999" style={styles.clearIcon} />
                    </TouchableOpacity>
                ) : null}
            </View>
            {error && (
                <View style={styles.errorContainer}>
                    <Text style={styles.errorText}>{error}</Text>
                </View>
            )}
            {!loading && books.length === 0 ? (
                <View style={styles.emptyContainer}>
                    <Icon name="search" size={50} color="#ccc" />
                    <Text style={styles.emptyTitle}>
                        {keyword ? `未找到"${keyword}"相关的书籍` :
                            category ? `未找到"${category}"分类的书籍` :
                                '暂无相关书籍'}
                    </Text>
                    <Text style={styles.emptySubtitle}>
                        试试其他关键词或者分类吧
                    </Text>
                </View>
            ) : (
                <FlatList
                    data={books}
                    renderItem={renderBookItem}
                    keyExtractor={item => item.id.toString()}
                    numColumns={2}
                    contentContainerStyle={styles.bookList}
                    columnWrapperStyle={styles.bookRow}
                />
            )}
        </View>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff',
    },
    searchBar: {
        flexDirection: 'row',
        alignItems: 'center',
        backgroundColor: '#f5f5f5',
        borderRadius: 20,
        paddingHorizontal: 15,
        paddingVertical: 10,
        margin: 15,
        marginTop: 10,
    },
    searchIcon: {
        marginRight: 10,
        padding: 5,
    },
    searchInput: {
        flex: 1,
        fontSize: 16,
        color: '#333',
        padding: 0,
    },
    clearIcon: {
        marginLeft: 10,
        padding: 5,
    },
    loadingContainer: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
    errorContainer: {
        padding: 15,
        backgroundColor: '#ffebee',
        margin: 10,
        borderRadius: 5,
    },
    errorText: {
        color: '#c62828',
    },
    bookList: {
        padding: ITEM_MARGIN,
    },
    bookRow: {
        justifyContent: 'flex-start',
    },
    bookItem: {
        width: ITEM_WIDTH,
        marginBottom: ITEM_MARGIN,
        marginRight: ITEM_MARGIN,
        backgroundColor: '#fff',
        borderRadius: 8,
        overflow: 'hidden',
    },
    imageContainer: {
        position: 'relative',
    },
    bookCover: {
        width: '100%',
        height: ITEM_WIDTH * 1.4, // 保持图片比例
        borderRadius: 4,
    },
    bookInfo: {
        padding: 8,
    },
    bookTitle: {
        fontSize: 14,
        fontWeight: 'bold',
        color: '#333',
        marginBottom: 4,
    },
    bookAuthor: {
        fontSize: 12,
        color: '#666',
        marginBottom: 4,
    },
    updateTime: {
        fontSize: 12,
        color: '#999',
        marginBottom: 2,
    },
    commentCount: {
        fontSize: 12,
        color: '#999',
    },
    categoryTag: {
        position: 'absolute',
        top: 8,
        right: 8,
        paddingHorizontal: 8,
        paddingVertical: 4,
        borderRadius: 12,
        opacity: 0.9,
    },
    categoryText: {
        fontSize: 12,
        color: '#666',
        fontWeight: '500',
    },
    emptyContainer: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        paddingHorizontal: 40,
    },
    emptyTitle: {
        fontSize: 16,
        color: '#666',
        marginTop: 20,
        marginBottom: 8,
        textAlign: 'center',
    },
    emptySubtitle: {
        fontSize: 14,
        color: '#999',
        textAlign: 'center',
    },
});

export default Search; 